<?php
/*
 * @Author: 李志刚
 * @CopyRight: 2020-2030 衡水山木枝技术服务有限公司
 * @Date: 2021-07-01 09:37:19
 * @Description: 拼多多订单拉取
 * @LastEditors: 李志刚
 * @LastEditTime: 2021-07-06 17:40:04
 * @FilePath: /qingshanERP/app/Console/Commands/Pdd/PullOrder.php
 */

namespace App\Console\Commands\Pdd;

use DB;
use App\Customize\PddRequest;
use App\Models\QingShanERP\GoodSpec;
use Illuminate\Console\Command;
use App\Models\QingShanERP\Shop;
use App\Models\QingShanERP\Order;
use App\Models\QingShanERP\OrderGood;
use App\Models\QingShanERP\OrderPddData;

class PullOrder extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'pdd-pull-order';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '拼多多订单拉取';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        try {
            $start_time = strtotime(date('2021-06-01 00:00:00'));
            // 找所有门店
            $all_shop = Shop::where('type',4)->where('del_flag',0)->where('id',1)->get();
            foreach ($all_shop as $s) {
                // 如果token有效
                if ($s->expires_at >= time() && !is_null($s->access_token)) {
                    for ($i = 0; $i < 30; $i++) {
                        $data = [];
                        $params['access_token'] = $s->access_token;
                        $params['timestamp'] = strval(time());
                        $params['order_status'] = 5;
                        $params['start_confirm_at'] = $start_time + $i * 24 * 60 * 60;
                        $params['end_confirm_at'] = $start_time + ($i + 1) * 24 * 60 * 60;
                        dump(date('Y-m-d H:i:s', $params['start_confirm_at']) . ' - ' . date('Y-m-d H:i:s', $params['end_confirm_at']));
                        $params['page_size'] = 100;
                        $params['refund_status'] = 5;
                        $params['use_has_next'] = true;
                        $params['page'] = 1;
                        // 循环拉取一天的订单
                        $has_next = true;
                        while ($has_next) {
                            $tmp = PddRequest::request('pdd.order.list.get', $params);
                            if (!isset($tmp['order_list_get_response'])) {
                                dump($tmp['error_response']['error_msg']);
                            }
                            else{
                                $has_next = $tmp['order_list_get_response']['has_next'];
                                if ($has_next) {
                                    $params['page'] = $params['page'] + 1;
                                }
                                if (is_array($tmp['order_list_get_response']['order_list'])) {
                                    $data = array_merge($data, $tmp['order_list_get_response']['order_list']);
                                }
                            }
                            sleep(1);
                        }
                        dump(count($data));
                        // 开始插入数据
                        DB::beginTransaction();
                        try {
                            foreach($data as $d){
                                dump('当前订单号：'.$d['order_sn']);
                                $order_create = ['type'=>$s->type,'shop_id'=>$s->id, 'order_sn' => $d['order_sn'], 'trade_type' => $d['trade_type'], 'confirm_time' => $d['confirm_time'], 'last_updated_at' => $d['updated_at'], 'confirm_status' => $d['confirm_status'], 'order_status' => $d['order_status'],'after_sales_status' => $d['after_sales_status'], 'pay_amount' => $d['pay_amount'], 'logistics_id' => $d['logistics_id'],'tracking_number' => $d['tracking_number']];
                                if ($d['shipping_time'] != '') {
                                    $order_create['shipping_time'] = $d['shipping_time'];
                                }
                                if ($d['receive_time'] != '') {
                                    $order_create['receive_time'] = $d['receive_time'];
                                }
                                if (isset($d['remark_tag'])) {
                                    $order_create['remark_tag'] = $d['remark_tag'];
                                    $order_create['remark_tag_name'] = $d['remark_tag_name'];
                                }
                                $order = Order::create($order_create);
                                // 订单附表，拼多多表
                                $pdd_create = ['order_id'=>$order->id, 
                                                'created_time' => $d['created_time'], 
                                                'receiver_name' => $d['receiver_name'], 
                                                'receiver_phone' => $d['receiver_phone'], 
                                                'receiver_address' => $d['receiver_address'], 
                                                'address' => $d['address'], 
                                                'province' => $d['province'], 
                                                'city' => $d['city'], 
                                                'town' => $d['town'], 
                                                'goods_amount' => $d['goods_amount'],
                                                'discount_amount' => $d['discount_amount'],
                                                'postage' => $d['postage'],
                                                'order_change_amount' => $d['order_change_amount'],
                                                'pay_no' => $d['pay_no'],
                                                'pay_type' => $d['pay_type'],
                                                
                                                'refund_status' => $d['refund_status'],
                                                'last_ship_time' => $d['last_ship_time'],
                                                'remark' => $d['remark'],
                                                'self_contained' => $d['self_contained'],
                                                'risk_control_status' => $d['risk_control_status'],
                                                'shipping_type' => $d['shipping_type'],
                                                'yyps_date' => $d['yyps_date'],
                                                'delivery_one_day' => $d['delivery_one_day'],
                                                'duoduo_wholesale' => $d['duoduo_wholesale'],
                                                'mkt_biz_type' => $d['mkt_biz_type'],
                                                'free_sf' => $d['free_sf'],
                                                'is_pre_sale' => $d['is_pre_sale'],
                                                'invoice_status' => $d['invoice_status'],
                                                'is_pre_sale' => $d['is_pre_sale'],
                                                'buyer_memo' => $d['buyer_memo'],
                                                'stock_out_handle_status' => $d['stock_out_handle_status'],
                                                'is_stock_out' => $d['is_stock_out'],
                                            ];
                                if ($d['pay_time'] != '') {
                                    $pdd_create['pay_time'] = $d['pay_time'];
                                }
                                if ($d['yyps_time'] != '') {
                                    $pdd_create['yyps_time'] = $d['yyps_time'];
                                }
                                if ($d['urge_shipping_time'] != '') {
                                    $pdd_create['urge_shipping_time'] = $d['urge_shipping_time'];
                                }
                                OrderPddData::create($pdd_create);
                                // 商品附表
                                $goods_insert = [];
                                $date = date('Y-m-d H:i:s');
                                foreach ($d['item_list'] as $g) {
                                    $good = GoodSpec::where('sku_id', $g['sku_id'])->where('del_flag',0)->first();
                                    if (!is_null($good)) {
                                        $goods_insert[] = [
                                            'order_id'=>$order->id,
                                            'good_id'=> $good->good_id,
                                            'good_spec_id'=> $good->id,
                                            'goods_spec'=>$g['sku_id'],
                                            'goods_name' => $g['goods_name'],
                                            'good_spec_name' => $g['goods_spec'],
                                            'goods_price' => $g['goods_price'],
                                            'goods_img' => $g['goods_img'],
                                            'goods_count' => $g['goods_count'],
                                            'gift_flag' => 0,
                                            'created_at' =>$date,
                                            'updated_at' => $date,
                                        ];
                                    }
                                }
                                foreach($d['gift_list'] as $gift){
                                    $good = GoodSpec::where('sku_id', $g['sku_id'])->where('del_flag', 0)->first();
                                    if (!is_null($good)) {
                                        $goods_insert[] = [
                                            'order_id' => $order->id,
                                            'good_id' => $good->good_id,
                                            'good_spec_id' => $good->id,
                                            'goods_spec' => $gift['sku_id'],
                                            'goods_name' => $gift['goods_name'],
                                            'good_spec_name' => $gift['goods_spec'],
                                            'goods_price' => $gift['goods_price'],
                                            'goods_img' => $gift['goods_img'],
                                            'goods_count' => $gift['goods_count'],
                                            'gift_flag' => 0,
                                            'created_at' => $date,
                                            'updated_at' => $date,
                                        ];
                                    }
                                }
                                OrderGood::insert($goods_insert);
                            }
                            DB::commit();
                        } catch (\Throwable $th) {
                            DB::rollback();
                            dd($th->getMessage());
                        }
                        dump('门店<' . $s->shopname . ' - '.date('Y-m-d H:i:s', $params['start_confirm_at']).'>订单拉取完成');
                    }
                    dump('门店<'.$s->shopname.'>拉取完成');
                }
            }
            dd('success');
        } catch (\Throwable $th) {
            dd($th->getMessage());
        }
    }
}
